package com.zklh.leetcode.top100.problem32;

/**
 * 最長有效括號算法實現
 *
 * @Author tongnan
 * @Date 2024/2/28
 * @Version 1.0
 */
public class Solution {
    public int longestValidParentheses(String s) {
        int longest = 0;
        char[] chars = s.toCharArray();
        int balance = 0;
        int startPrev = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(') {
                balance += 1;
            }
            if (chars[i] == ')') {
                balance -= 1;
            }
            if (balance == 0) {
                longest = Math.max(longest, i - startPrev);
            }
            if (balance < 0) {
                balance = 0;
                startPrev = i;
            }
        }
        balance = 0;
        int endBack = chars.length;
        for (int i = chars.length-1; i >= 0; i--) {
            if (chars[i] == '(') {
                balance -= 1;
            }
            if (chars[i] == ')') {
                balance += 1;
            }
            if (balance == 0) {
                longest = Math.max(longest, endBack - i);
            }
            if (balance < 0) {
                balance = 0;
                endBack = i;
            }
        }
        return longest;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestValidParentheses("(()"));
        System.out.println(solution.longestValidParentheses(")()())"));
        System.out.println(solution.longestValidParentheses(""));
    }
}